/**
 * @ngdoc module
 * @name diary.controllers
 * @description
 *   工作日志模块控制器
 */
angular.module('diary.controllers', [])

/**
 * @ngdoc controller
 * @name DiaryIndexCtrl
 * @module diary.controllers
 * @description
 *   日志主页控制器
 */
  .controller('DiaryIndexCtrl', function($scope, $ionicModal, $ionicLoading, $state, User, Utils, Diary) {
    $ionicLoading.show();
    User.getAuthority().success(function(res){
        if(res.isSuccess){
          if(res.data.diary){
            $scope.openSettingModel = function() {
              $ionicModal.fromTemplateUrl('templates/diary/diary-setting.html', {
                scope: $scope,
                animation: 'slide-in-up'
              })
                .then(function(modal) {
                  $scope.settingModel = modal;
                  $scope.settingModel.show();

                  $scope.formData = {
                    defaultShareList: '',
                    direct: 0,
                    attentionList: ''
                  };

                  Diary.setting().success(function(res) {
                    if(res.isSuccess) {
                      $scope.dashboardConfig = res.dashboardConfig;
                      angular.extend($scope.formData, res.data, {
                        direct: +res.data.direct
                      });
                    }
                  });

                  $scope.submit = function() {
                    $ionicLoading.show();
                    Diary.savesetting({
                      defaultShareList: User.addPrefix($scope.formData.defaultShareList),
                      direct: $scope.formData.direct,
                      attentionList: User.addPrefix($scope.formData.attentionList),
                    }).success(function(res) {
                      if (res.isSuccess === true) {
                        $scope.settingModel.hide();
                      }
                    })
                      .finally($ionicLoading.hide);
                  }
                })
            };
          } else{
            Utils.promptNoPermission();
          }
        }
      }
    ).finally($ionicLoading.hide);
  })
/**
 * @ngdoc controller
 * @name DiaryPersionalCtrl
 * @module diary.controllers
 * @description
 *   我的日志列表页控制器
 */
  .controller('DiaryPersionalCtrl', function($scope, $ionicListDelegate, $ionicScrollDelegate, $ionicLoading, dateFilter, Utils, IbPopup, Diary) {

    $scope.list = [];
    $scope.loadMore = function() {
      return Diary.mine({
        page: $scope.pages ? $scope.pages.page + 2 : 1
      }).success(function(res) {
        if (res.isSuccess) {
          $ionicScrollDelegate.resize();
          $scope.list = $scope.list.concat(res.data);
          $scope.pages = res.pages;
        }
      });
    };
    $scope.loadMore();

    $scope.refresh = function() {
      $scope.list.length = 0;
      delete $scope.pages;
      $scope.loadMore().finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }

    $scope.groupByYearMonth = function(item) {
      return dateFilter(item.diarytime * 1000, 'yyyy年M月');
    };

    $scope.remove = function(item) {
      IbPopup.confirm({title: '确认删除日志？'}).then(function(flag) {
        if (flag) {
          $ionicListDelegate.closeOptionButtons();
          $ionicLoading.show();
          Diary.remove(item.diaryid)
            .success(function(res) {
              if(res.isSuccess) {
                Utils.eliminate($scope.list, item);
              } else {
                IbPopup.alert({ title: res.msg });
              }
            })
            .finally($ionicLoading.hide);
        }
      });
    };
  })

/**
 * @ngdoc controller
 * @name DiaryReviewCtrl
 * @module diary.controllers
 * @description
 *   日志评阅列表页控制器
 */
  .controller('DiaryReviewCtrl', function($scope, $state, $stateParams, $filter, $ionicHistory, $ionicScrollDelegate, User, dateFilter, Diary) {
    $scope.list = [];
    $scope.loadMore = function() {
      return Diary.allsubs({
        page: $scope.pages ? $scope.pages.page + 2 : 1
      }).success(function(res) {
        if (res.isSuccess) {
          $ionicScrollDelegate.resize();

          if(!res.diary || !res.diary.length) return;

          angular.forEach(res.diary, function(item) {
            item.isfavor = res.attentionList.indexOf(item.uid) !== -1;
          });

          $scope.list = $scope.list.concat(res.diary);
          $scope.pages = res.pages;
        }
      });
    };
    $scope.loadMore();

    $scope.refresh = function() {
      $scope.list.length = 0;
      delete $scope.pages;
      $scope.loadMore().finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }

    $scope.groupByTime = function(item) {
      return dateFilter(item.diarytime * 1000, 'EEEE MM-dd');
    };

    $scope.isToday = function(key) {
      return key == dateFilter(new Date(), 'EEEE MM-dd');
    };
  })

/**
 * @ngdoc controller
 * @name DiaryFollowCtrl
 * @module diary.controllers
 * @description
 *   日志关注列表页控制器
 */
  .controller('DiaryFollowCtrl', function($scope, $state, $stateParams, $filter, $ionicHistory, $ionicScrollDelegate, User, dateFilter, Diary ) {
    $scope.list = [];
    $scope.loadMore = function() {
      return Diary.other({
        page: $scope.pages ? $scope.pages.page + 2 : 1
      }).success(function(res) {
        if (res.isSuccess) {
          $ionicScrollDelegate.resize();
          $scope.list = $scope.list.concat(res.data);
          $scope.pages = res.pages;
        }
      });
    };
    $scope.loadMore();

    $scope.refresh = function() {
      $scope.list.length = 0;
      delete $scope.pages;
      $scope.loadMore().finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }

    $scope.groupByTime = function(item) {
      return dateFilter(item.diarytime * 1000, 'EEEE MM-dd');
    };

    $scope.isToday = function(key) {
      return key == dateFilter(new Date(), 'EEEE MM-dd');
    };
  })

/**
 * @ngdoc controller
 * @name DiaryDetailCtrl
 * @module diary.controllers
 * @description
 *   日志详细页控制器
 */
  .controller('DiaryDetailCtrl', function($scope, $rootScope, $state, $stateParams, $ionicLoading, $ionicActionSheet, $ionicModal, $ionicScrollDelegate, Utils, User, IbPopup, Diary, Settings, userInfoFilter) {

    // 上一篇、下一篇日志
    // @Todo:
    // 此处应该做路由跳转到新视图，但在目前 ionic 框架中，路由跳转会破坏历史视图导致无法直接返回列表页
    // 所以现在暂时做成了在当前视图加载其他日志的数据
    $scope.toDiary = function(id) {
      loadDiary(id);
      $ionicScrollDelegate.scrollTop();
    };

    $scope.showMore = function() {

      $scope.hideMore = $ionicActionSheet.show({
        buttons: [{
          text: '编辑'
        }],
        buttonClicked: function() {
          $state.go('diary.edit', {
            id: $scope.diary.diaryid
          })
          return true;
        },
        destructiveText: '删除',
        cancelText: '取消',
        destructiveButtonClicked: function() {
          IbPopup.confirm({title: '确认删除日志？'}).then(function(flag){
            if(flag){
              $ionicLoading.show();
              Diary.remove($scope.diary.diaryid)
                .success(function(res) {
                  if(res.isSuccess) {
                    Utils.clearStateCacheAndGo('diary.personal');
                  } else {
                    IbPopup.alert({ title: res.msg });
                  }
                })
                .finally($ionicLoading.hide);
            }
          });
          return true;
        }
      })
    };

    $scope.showCommentModal = function(type, cm) {
      $ionicModal.fromTemplateUrl('templates/diary/diary-comment.html', {
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal) {
          $scope.commentModel = modal;
          $scope.commentModel.show();

          if (type === 'reply') {
            $scope.comment.content = cm.touid ? '回复 @' + userInfoFilter(cm.uid, 'realname') + ' : ' : ''
          }

          modal.scope.commentType = type;
        });

      $scope.comment.submitting = false;
      $scope.comment.submit = function() {
        var that = this;
        var params = {
          content: this.content,
          type: type
        };

        if (that.stamp) {
          params.stamp = that.stamp.id;
        }

        if (type === 'comment') {
          params.rowid = $scope.diary.diaryid;
        } else if (type === 'reply') {
          params.tocid = cm.cid;
          // 如果直接回复评论，则
          // 否则，如果回复评论下的回复，则
          params.rowid = cm.tocid === '0' ? cm.cid : cm.rowid;
        }
        that.submitting = true;

        return Diary.addComment(params)
          .success(function(res) {
            // 发送评论成功后，更新本地列表中的数据
            that.content = '';
            if (that.stamp) {
              $scope.stampUrl = that.stamp.stamp;
            }
            $scope.commentModel.hide();

            $ionicLoading.show();
            Diary.get($scope.diary.diaryid).success(function(res) {
              $scope.commentList = res.list.map(function(cm) {
                return angular.extend({}, cm, {
                  realname: cm.user_info.realname,
                  avatar: cm.user_info.avatar_middle
                });
              });
            })
              .finally($ionicLoading.hide);
          })
          .finally(function() {
            that.submitting = false;
          });
      }
    };

    function loadDiary(id) {
      $ionicLoading.show();
      Diary.show(id)
        .success(function(res) {
          $scope.diary = res.diary;
          var imgReg = /<img[^>]+src=['"](\/data\/ueditor\/image[^'"]+)['"]+/g;

          res.diary.content = res.diary.content.replace(imgReg, function(a, b) {
            return a.replace(b, Settings.hostUrl + b);
          });

          $scope.today = $scope.diary.diarytime;
          $scope.nextDay = $scope.diary.nextDiarytime;

          $scope.planned = res.data.originalPlanList;
          $scope.unplanned = res.data.outsidePlanList;
          $scope.plans = res.data.tomorrowPlanList;
          $scope.originalPlan = res.data.originalPlanList;

          $scope.next = res.prevAndNextPK.nextPK;
          $scope.prev = res.prevAndNextPK.prevPK;

          $scope.attach = res.attach;
          $scope.readers = $scope.diary.readeruid ? $scope.diary.readeruid.split(',') : [];
          $scope.editable = $scope.diary.uid == User.uid;

          $scope.isShare = res.isShare;
          $scope.isSup = res.isSup;
          $scope.dashboardConfig = res.dashboardConfig;

          //图章
          $scope.comment = {};
          $scope.comment.stamps = res.allStamps;

          // 过滤出需要使用的数据
          $scope.commentList = res.list.map(function(cm) {
            return angular.extend({}, cm, {
              realname: cm.user_info.realname,
              avatar: cm.user_info.avatar_middle
            });
          });
          $scope.stampUrl = res.stampUrl;
        })
        .finally($ionicLoading.hide);
    }

    loadDiary($stateParams.id);
  })

  .controller('DiaryFormCtrl', function($scope, $ionicLoading, $ionicModal, IbPopup, Diary, DiaryUtils, SCHEDULE) {
    $scope.formData = {
      originalPlan: [],
      planOutside: [],
      plan: [],
      uploadImagesPreviews: [],
      attachmentid: '',
      diaryContent: '',
      todayDate: '',
      plantime: ''
    };

    //获取默认分享人员
    Diary.setting().success(function(res) {
      if (res.isSuccess) {
        $scope.formData.shareuid = res.data.defaultShareList
      }
    });

    // 是否处于提交中的状态
    $scope.isSubmitting = false;
    $scope.SCHEDULE = SCHEDULE;

    $scope.addUnplanned = function() {
      $scope.formData.planOutside.push({
        content: '',
        schedule: '0'
      });
    };

    // 移除一条计划外
    $scope.removeUnplanned = function(index) {
      $scope.formData.planOutside.splice(index, 1);
    };

    // 增加一条计划
    $scope.addPlan = function() {
      $scope.formData.plan.push({
        content: ''
      });
    };

    // 移除一条计划
    $scope.removePlan = function(index) {
      $scope.formData.plan.splice(index, 1)
    };

    $scope.allowSubmit = function() {
      var fd = $scope.formData;
      return ((fd.planOutside[0] && fd.planOutside[0].content) || ($scope.originalPlanList && $scope.originalPlanList.length)) &&
        (fd.plan[0] && fd.plan[0].content) &&
        fd.diaryContent;
    };

    $scope.planfromschedule = function(todayDate) {
      $ionicLoading.show();
      Diary.planfromschedule(todayDate).success(function(res) {
        if (res.data.length > 0) {
          $scope.formData.planOutside = $scope.formData.planOutside.concat(res.data.map(function(c) {
            return {
              content: c.subject,
              schedule: '0'
            }
          }));
        } else {
          IbPopup.alert({
            title: '抱歉，你今天没有日程计划！'
          })
        }
      })
        .finally($ionicLoading.hide)
    };

    $scope.selectedStartDate = function() {
      DiaryUtils.selectedStartDate($scope)
    }

    $scope.selectedEndDate = function() {
      DiaryUtils.selectedEndDate($scope)
    };

    $scope.setRemind = function(plan) {
      DiaryUtils.setRemind($scope, plan)
    };

    $scope.delRemind = function(plan) {
      DiaryUtils.delRemind(plan)
    };

    $scope.openSharingModel = function() {
      $ionicModal.fromTemplateUrl('templates/diary/diary-sharing.html', {
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal) {
          $scope.sharingModel = modal;
          $scope.sharingModel.show();

        })
    };
  })

/**
 * @ngdoc controller
 * @name DiaryCreateCtrl
 * @module diary.controllers
 * @description
 *   日志新建页控制器
 */
  .controller('DiaryCreateCtrl', function($scope, $controller, $state, $ionicLoading, $ionicHistory, dateFilter, IbPopup, Utils, Diary, DiaryUtils, SCHEDULE) {
    $controller('DiaryFormCtrl', {
      $scope: $scope
    });

    $scope.submit = function() {
        // console.log($scope.formData)
        // debugger
      // 检查添加的所有内容
      var msg = '';
      if ($scope.formData.plan.length == 0 || !$scope.formData.plan[0].content) {
        msg = '至少填写一条工作计划';
      }
      if (!$scope.formData.diaryContent) {
        msg = '请填写工作总结'
      }
      if ($scope.formData.planOutside.length <= 0 || $scope.formData.originalPlan.length <= 0) {
        msg = '至少填写一条工作记录';
      }
      if (msg) {
        IbPopup.alert({
          title: msg
        })
      } else {
        Diary.create(DiaryUtils.handleFormData($scope.formData))
          .success(function() {
              Utils.clearStateCacheAndGo('diary.personal');
          })
          .finally(function() {
              $scope.isSubmitting = false;
          });
      }
    }

    // 获取原计划等数据
    $scope.$watch('formData.todayDate', function(date, oldDate) {
      if (date) {
        $scope.formData.plantime = dateFilter(+new Date(date) + 86400000, 'yyyy-MM-dd');

        $ionicLoading.show();
        Diary.add(date).success(function(res) {
          if (res.isSuccess) {
            // 是否安装了日程模块，用于判断是否支持提醒功能
            $scope.isInstallCalendar = res.isInstallCalendar;
            // 工作时间段
            $scope.workStart = res.workStart;
            // 后台配置项
            $scope.dashboardConfig = res.dashboardConfig;
            $scope.originalPlanList = res.data.originalPlanList;

            // 组合 formData 数据
            $scope.formData.originalPlan = {};
            angular.forEach(res.data.originalPlanList, function(item) {
              $scope.formData.originalPlan[item.recordid] = item.schedule;
            });
            $scope.formData.plan = [{}];
            $scope.formData.planOutside = [{ schedule: '10' }];
          } else {
            IbPopup.alert({title: res.msg }).then(function(){
              $state.go('diary.index');
            });
            // $scope.formData.todayDate = oldDate;
          }
        })
          .finally($ionicLoading.hide);
      }
    });

    $scope.formData.todayDate = dateFilter(new Date(), 'yyyy-MM-dd');
  })

/**
 * @ngdoc controller
 * @name DiaryEditCtrl
 * @module diary.controllers
 * @description
 *   日志编辑页控制器
 */
  .controller('DiaryEditCtrl', function($scope, $controller, $state, $stateParams, $ionicLoading, $ionicHistory, Utils, User, IbPopup, Diary, DiaryUtils, SCHEDULE) {
    $controller('DiaryFormCtrl', {
      $scope: $scope
    });

    $scope.selectedStartDate = $scope.selectedEndDate = angular.noop;

    $scope.submit = function() {
      // 检查添加的所有内容
      var msg = '';
      if ($scope.formData.plan.length == 0 || !$scope.formData.plan[0].content) {
        msg = '至少填写一条工作计划';
      }
      if (!$scope.formData.diaryContent) {
        msg = '请填写工作总结'
      }
      if (!$scope.formData.planOutside.length <= 0 || $scope.formData.originalPlan.length <= 0) {
        msg = '至少填写一条工作记录';
      }
      if (msg) {
        IbPopup.alert({
          title: msg
        })
      } else {
        Diary.update(DiaryUtils.handleFormData($scope.formData))
          .success(function() {
              Utils.clearStateCacheAndGo('diary.personal');
          })
          .finally(function() {
              $scope.isSubmitting = false;
          });
      }
    };

    $ionicLoading.show();

    Diary.edit($stateParams.id)
      .success(function(res) {
        if(!res.isSuccess) {
          IbPopup.alert({ title: res.msg }).then(function() {
            $ionicHistory.goBack();
          });
        } else {
          // 是否安装了日程模块，用于判断是否支持提醒功能
          $scope.isInstallCalendar = res.isInstallCalendar;
          // 工作时间段
          $scope.workStart = res.workStart;
          // 后台配置项
          $scope.dashboardConfig = res.dashboardConfig;
          $scope.originalPlanList = res.data.originalPlanList;

          $scope.formData.originalPlan = {};
          angular.forEach(res.data.originalPlanList, function(item) {
            $scope.formData.originalPlan[item.recordid] = item.schedule;
          });
          $scope.formData.planOutside = res.data.outsidePlanList;
          $scope.formData.plan = res.data.tomorrowPlanList;
          $scope.formData.id = res.diary.diaryid;
          $scope.formData.diaryContent = res.diary.content;
          $scope.formData.shareuid = User.removePrefix(res.diary.shareuid);

          var today = res.diary.diarytime,
            nextDay = res.diary.nextDiarytime;

          $scope.formData.todayDate = today.year + '-' + today.month + '-' + today.day;
          $scope.todayWeekday = today.weekday;
          $scope.formData.plantime = nextDay.year + '-' + nextDay.month + '-' + nextDay.day;
          $scope.tomorrowWeekday = nextDay.weekday;
        }
      })
      .finally($ionicLoading.hide);
  })

/**
 * @ngdoc controller
 * @name DiaryUnderingCtrl
 * @module diary.controllers
 * @description
 *   日志下属日志控制器
 */
  .controller('DiaryUnderingCtrl',function($scope, $stateParams, $ionicHistory, $ionicScrollDelegate, $state, userInfoFilter, dateFilter, Diary){
    $scope.list = [];
    $scope.title = userInfoFilter($stateParams.id, 'realname');

    $scope.loadMore = function() {
      return Diary.personal({
        uid: $stateParams.id,
        page: $scope.pages ? $scope.pages.page + 2 : 1
      }).success(function(res) {
        if (res.isSuccess) {
          $ionicScrollDelegate.resize();
          $scope.list = $scope.list.concat(res.diary);
          $scope.pages = res.pages;
          $scope.isattention = res.isattention;
          $scope.dashboardConfig = res.dashboardConfig;
        }
      });
    };
    $scope.loadMore();

    $scope.refresh = function() {
      $scope.list.length = 0;
      delete $scope.pages;
      $scope.loadMore().finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    };

    $scope.groupByMonth = function(item) {
      return dateFilter(item.diarytime * 1000, 'M月');
    };

    $scope.attention = function() {
      Diary.attention($stateParams.id).success(function() {
        $scope.isattention = 1;
      })
    };

    $scope.unattention = function() {
      Diary.unattention($stateParams.id).success(function() {
        $scope.isattention = 0;
      })
    };
  });